package com.feng.study.demo.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUCDemo02 {
    public static void main(String[] args) {
        // 获取CPU核数
        int cpuNum = Runtime.getRuntime().availableProcessors();
        System.out.println("cup核数："+cpuNum);

        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        Ticket ticket = new Ticket();
//        new Thread(()->{for (int i = 0; i < 30; i++) ticket.sale();},"A").start();
//        new Thread(()->{for (int i = 0; i < 30; i++) ticket.sale();},"B").start();
//        new Thread(()->{for (int i = 0; i < 30; i++) ticket.sale();},"C").start();

        // 永远是sale02先执行
        // 因为 synchronized 锁的对象是方法的调用者
        new Thread(()->ticket.sale02(),"A").start();
        new Thread(()->ticket.sale03(),"B").start();
        // 永远是sale04先执行,没有加锁，不受影响
        new Thread(()->ticket.sale04(),"C").start();
    }
}

class Ticket{
    private int number=20;

    public synchronized void sale(){
        if (number>0){
            number--;
            System.out.println(Thread.currentThread().getName()+":卖出票1张，剩余数量："+number);
        }
    }

    // 锁的对象是方法的调用者，
    public synchronized void sale02(){
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"aaaaa");
    }

    public synchronized void sale03(){
        System.out.println(Thread.currentThread().getName()+"bbbbb");
    }

    public void sale04(){
        System.out.println(Thread.currentThread().getName()+"ccccc");
    }
}
